<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="professions">
          <el-form-item label="所属专业" size="small">
            <el-select v-model="searchForm.professions" placeholder="请选择所属专业">
              <el-option value="" label="全部"></el-option>
              <el-option
                v-for="item in professions"
                :key="item.professionId"
                :label="item.professionName"
                :value="item.professionName">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="团队名称" size="small">
            <el-input v-model="searchForm.teamName"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>
      <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="440px" @close="closeOuterVisible">
        <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="100px">
          <el-form-item prop="teamName" label="团队名称" size="small">
            <el-input v-model="teamRow.teamName" @blur="teamNameBlur"></el-input>
          </el-form-item>
          <el-form-item prop="teamHead" label="团队负责人" size="small">
            <el-input v-model="teamRow.teamHead"></el-input>
          </el-form-item>
          <el-form-item prop="typeId" label="团队类型" size="small">
            <el-select v-model="teamRow.typeId" placeholder="请选择团队类型">
              <el-option
                v-for="item in typeNames"
                :key="item.typeId"
                :label="item.typeName"
                :value="item.typeId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="管理费率" size="small" v-if="roleType===0 || roleType===1|| roleType===5">
            <el-input type="number" v-model.number="teamRow.managementFeeRate">
              <span slot="suffix">%</span>
            </el-input>
          </el-form-item>
          <el-form-item prop="address" label="所在地址" size="small">
            <area-cascader v-model="teamRow.addressId" v-if="isAddress" placeholder="请选择省市" :data="pca"
                           @change="addressChange()"></area-cascader>
            <el-input type="textarea" v-model="teamRow.address" placeholder="请填写详细地址"></el-input>
          </el-form-item>
          <el-form-item label="所属专业" size="small">
            <el-checkbox-group v-model="teamRow.professions">
              <el-checkbox v-for="item in professions" :label="item.professionName">{{item.professionName}}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="备注说明" size="small">
            <el-input type="textarea" v-model="teamRow.remark"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click :disabled="isTeamName">确定</el-button>
          <el-button size="small" @click="outerVisible = false">取消</el-button>
        </div>
      </el-dialog>
      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    </div>
    <my-table
      :data="tableData"
      :col-configs="roleType===0 || roleType===1|| roleType===5 ? colConfigs : roleTypeConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
    >
      <el-table-column
        slot="opt"
        label="操作"
        fixed="right"
        width="80">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editTeam(scope.row.teamId)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
  import {
    deleteTeams,
    getTeamsList,
    insertTeams,
    selectProfessions,
    selectTeam,
    selectTypeName,
    updateTeams,
    isTeam
  } from '@/api/teams'
  import myTable from '@/components/myTable'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      return {
        colConfigs: [
          { prop: 'teamName', label: '团队名称', minWidth: '10%', fixed: true },
          { prop: 'teamHead', label: '负责人', minWidth: '10%' },
          { prop: 'typeName', label: '团队类型', minWidth: '10%' },
          { prop: 'professions', label: '所属专业', minWidth: '25%' },
          { prop: 'managementFeeRate', label: '管理费率(%)', minWidth: '20%' },
          { prop: 'address', label: '办公地址', minWidth: '25%' },
          { prop: 'remark', label: '备注说明', minWidth: '20%' },
          { slot: 'opt' }
        ],
        roleTypeConfigs: [
          { prop: 'teamName', label: '团队名称', minWidth: '10%', fixed: true },
          { prop: 'teamHead', label: '负责人', minWidth: '10%' },
          { prop: 'typeName', label: '团队类型', minWidth: '10%' },
          { prop: 'professions', label: '所属专业', minWidth: '25%' },
          { prop: 'address', label: '办公地址', minWidth: '25%' },
          { prop: 'remark', label: '备注说明', minWidth: '20%' },
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        professions: [],
        typeNames: [],
        listLoading: true,
        dialogTitle: '新增团队信息',
        dialogType: 0,
        teamRow: {
          professions: []
        },
        teamRowClear: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        isAddress: false, // 地区新增 修改 摧毁 生成组件
        isRender: false, // 判断地区是否编辑
        pca: pca,
        rules: {
          teamName: [
            { required: true, message: '请输入团队名称', trigger: 'change' }
          ],
          teamHead: [
            { required: true, message: '请输入团队负责人', trigger: 'change' }
          ],
          typeId: [
            { required: true, message: '请选择团队', trigger: 'change' }
          ],
          address: [
            { required: true, message: '请输入办公地址', trigger: 'change' }
          ]
        },
        visible: false,
        isTeamName: false // 判断是否有重复团队
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
      this.selectProfessions()
      this.selectTypeName()
    },
    computed: {
      roleType() {
        return this.$store.state.user.roleType
      }
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.listLoading = true
        console.log(this.searchFormList)
        getTeamsList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          this.listLoading = false
        })
      },
      selectProfessions() {
        selectProfessions().then(response => {
          this.professions = response.responseBody
        })
      },
      selectTypeName() {
        selectTypeName().then(response => {
          this.typeNames = response.responseBody
        })
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        this.outerVisible = true
        this.isAddress = true
        this.isTeamName = false
        this.dialogTitle = '新建团队信息'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.dialogType = 1
      },
      editTeam(teamId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.isAddress = true
        this.isRender = true
        this.isTeamName = false
        this.dialogTitle = '修改团队信息'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 0
        const params = {
          teamId: teamId
        }
        selectTeam(params).then(response => {
          this.teamRow = Object.assign({}, this.teamRow, response.responseBody)
          this.teamRow.professions = this.teamRow.professions.split(',')
          this.teamRow.addressId = [this.teamRow.provinceId.toString(), this.teamRow.cityId.toString()]
          this.teamRow.address = this.teamRow.address
        })
      },
      closeOuterVisible() {
        this.isAddress = false
      },
      submitForm(formName) {
        const params = {
          teamName: this.teamRow.teamName,
          teamHead: this.teamRow.teamHead,
          typeId: this.teamRow.typeId,
          managementFeeRate: this.teamRow.managementFeeRate || 0,
          provinceId: parseInt(this.teamRow.provinceId),
          cityId: parseInt(this.teamRow.cityId),
          address: this.teamRow.address || '',
          remark: this.teamRow.remark || ''
        }
        params.professions = this.teamRow.professions.join(',')
        if (!this.dialogType) {
          params.teamId = this.teamRow.teamId
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.dialogType) {
              insertTeams(params).then(response => {
                if (response.resultCode !== 3) {
                  this.outerVisible = false
                  this.isAddress = false
                  this.fetchData()
                }
              })
            } else {
              updateTeams(params).then(response => {
                console.log(response)
                this.outerVisible = false
                this.isAddress = false
                this.fetchData()
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          teamId: scope.row.teamId,
          isDel: 1
        }
        deleteTeams(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      addressChange() {
        this.teamRow.provinceId = this.teamRow.addressId[0]
        this.teamRow.cityId = this.teamRow.addressId[1]
        if (!this.isRender) {
          this.teamRow.address = this.pca[86][this.teamRow.addressId[0]] + this.pca[this.teamRow.addressId[0]][this.teamRow.addressId[1]]
        } else {
          this.isRender = false
        }
      },
      teamNameBlur() {
        if (this.dialogType === 1) {
          const params = {
            teamName: this.teamRow.teamName
          }
          isTeam(params).then(response => {
            if (response.resultCode === 1) {
              this.isTeamName = false
            } else {
              this.isTeamName = true
            }
          })
        }
      }
    },
    mounted() {
      console.log(this.pca)
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      margin-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        margin: 0 20px;
      }
      .el-dialog {
        textarea {
          margin-top: 10px;
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
